﻿using Newtonsoft.Json;
using Senparc.Weixin.MP.CommonAPIs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }



        #region [微信扫码注册]

        public JsonResult CreateWeiXinQrcode()
        {
            Result result = new Result();
            result.success = true; 
            if (string.IsNullOrEmpty(MvcApplication.MyToken))
            {
                MvcApplication.MyToken = GetAccessToken("wx3b2bd5e66afd1940", "9c7fbd6d3f0beb635f1c97b6f0d0a16e");//印讯公众号
            }
            var accessToken = MvcApplication.MyToken; 
            //var accessToken = wxhelper.GetAccessToken("wx9fa1d2dca47c119b", "d306322a7d3e30de3224eb4ec0d394c5");//彩印通公众号
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                throw new Exception("获取Token失败");
            }
            var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;

            var scene_id = DateTime.Now.ToFileTime().ToString();
            scene_id = scene_id.Substring((scene_id.Length - 9), 9); 
            var param = "{ \"expire_seconds\": 120, \"action_name\": \"QR_SCENE\", \"action_info\": { \"scene\": { \"scene_id\": "+ scene_id + "} } }";
            MvcApplication.listWxModel.Add(new Models.WxModel() {
                scene_id = scene_id.ToString(),
                createTime=DateTime.Now, 
            }); 
            var resu = Core.Helper.HttpHelper.Post(url, param);
            if (resu.StartsWith("{") && resu.EndsWith("}"))
            {
                dynamic obj = JsonConvert.DeserializeObject(resu);
                string ticket = obj.ticket + "";
                result.Data = new {
                    ticket = ticket,
                    scene_id= scene_id.ToString(),
                };
            }
            else
            {
                result.success = false;
            }
            return Json(result);
        }

        public JsonResult QrWxConnect()
        {
            Result result = new Result();
            result.status = 0;
            result.success = true;
            var ticket = Request["token"];
            var ttt = Request["ttt"];
            var wxModel = MvcApplication.listWxModel.FirstOrDefault(x => x.scene_id == ticket && x.isscan == true);
            if (wxModel != null && (DateTime.Now - wxModel.scanTime).TotalMinutes < 3)
            {
                result.status = 1;//扫描成功
            }
            return Json(result);
        }


        #endregion



        /// <summary>
        /// 获取访问令牌
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public string GetAccessToken(string appid, string secret, bool IsGetNew = false)
        {
            string result = "";
            if (!string.IsNullOrWhiteSpace(appid) && !string.IsNullOrWhiteSpace(secret))
            {
                try
                {
                    if (IsGetNew)
                    {
                        result = AccessTokenContainer.TryGetToken(appid, secret, true);
                    }
                    else
                    {
                        result = AccessTokenContainer.TryGetToken(appid, secret);
                    }
                }
                catch (Exception ex)
                {
                    Core.Log.Error("[WXACT]appId=" + appid + ";appSecret=" + secret + ";" + ex.Message);
                }
            }
            else
            {
                throw new Exception("未配置微信公众信息");
            }
            return result;
        }

    }

    public class Result
    {
        public bool success { get; set; }

        public string msg { get; set; }
        /// <summary>
        /// 状态
        /// <para>1表成功</para>
        /// </summary>
        public int status { get; set; }

        public object Data { get; set; }
    }
}